import { Message } from 'element-ui';
import axios from 'axios';
import router from '@/router';
import store from '@/store';

const instance = axios.create({
  baseURL: 'http://127.0.0.1:5000',
});

// 设置请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (store.state.token) {
      config.headers.Authorization = store.state.token;
    }
    return config;
  },
  function (error) {
    router.replace('/login');
    return Promise.reject(error);
  }
);
// 设置响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    let status = error.response.status;
    if (status === 401) {
      console.log('我重新发请求拿token');
      let { data } = await axios({
        method: 'post',
        url: 'http://127.0.0.1:5000/getRefreshToken',
        data: { refreshToken: store.state.refreshToken },
      });
      let { code, token } = data;
      if (code === 20000) {
        console.log('我带token回来了');
        store.commit('addToken', token);
        instance(error.config);
        location.reload();
      } else {
        // 说明是无效的Token，提示给用户，把本地存储中的Token重置为空，并跳转到登录界面
        Message({
          message: '401 权限不够哦',
          type: 'warning',
        });
        store.commit('delToken');
        router.replace('/login');
        location.reload();
      }
    }
    return Promise.reject(error);
  }
);

export default instance;
